<template>
  <el-dialog v-model="isShow" class="login-dialog" title="登录" width="400">
    <el-form
      ref="ruleFormRef"
      style="max-width: 400px"
      :model="ruleForm"
      status-icon
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" show-password />
      </el-form-item>
      <div class="mt-10 login-tip">
        <span class="colorFlag" @click="handleRegister">立即注册</span>
        <span class="colorFlag" @click="handleForget">忘记密码?</span>
      </div>
      <el-form-item>
        <el-button class="dlBtn" type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
        <el-button class="cacleBtn" @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { userLogin } from '@/api/user.js';
import { useUsersStore } from '@/store/user';
import { setToken } from '@/utils/auth.js';
import { ElMessage } from 'element-plus';
import { ref, watch } from 'vue';

const { setUserInfo: setUserStore } = useUsersStore();
const emis = defineEmits(['showLogin', 'showRegister']);

const props = defineProps({
  isShowLogin: {
    type: Boolean,
    default: true,
  },
});

const ruleForm = ref({});
const isShow = ref(false);

const submitForm = async () => {
  const res = await userLogin(ruleForm.value);
  if (res.code === 200) {
    ElMessage({
      message: '登录成功',
      type: 'success',
    });
    setToken(res.data.token);
    setUserStore(res.data.userInfo);
    isShow.value = false;
    emis('showLogin', false);
  }
};
const resetForm = () => {
  isShow.value = false;
  emis('showLogin', false);
};

// 立即注册
const handleRegister = () => {
  emis('showLogin', false);
  emis('showRegister', true);
};
const handleForget = () => {};

watch(
  () => props.isShowLogin,
  (val) => {
    isShow.value = val;
  },
);

watch(
  () => isShow.value,
  (val) => {
    emis('showLogin', val);
  },
);
</script>

<style scoped lang="scss">
.login-box {
  width: 400px;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dlBtn,
.cacleBtn {
  width: 47%;
  margin-left: 2.5%;
}
</style>
